// Zoop Board by Andrew Davies

"use strict";

function ZoopBoard( 
	scrPosX, scrPosY, 
	totalBoardPosX, totalBoardPosY,
	moveDirX, moveDirY, 
	addPosX, addPosY, 
	addDirX, addDirY, 
	colourA, colourB,
	baddyDir )
{
	this.scrPos = new Vec2( scrPosX, scrPosY );
	this.totalBoardPos = new Vec2( totalBoardPosX, totalBoardPosY );
	this.moveDir = new Vec2( moveDirX, moveDirY );
	this.addPos = new Vec2( addPosX,addPosY );
	this.addDir = new Vec2( addDirX, addDirY );
	this.colourA = colourA;
	this.colourB = colourB;
	this.baddyDir = baddyDir;
	
	this.baddies = new Array();
	
	this.addBaddies = function( frameIdx )
	{
		// Move existing baddies
		for( var baddyIdx in this.baddies )
		{
			this.baddies[ baddyIdx ].move( this.moveDir );			
		}	
		
		// Add a new row
		var newBabbyBoardPos = new Vec2( this.addPos.x, this.addPos.y );
		for( var newBaddyIdx = 0; newBaddyIdx < SUB_BOARD_NUM_UNITS_Y; newBaddyIdx++ )
		//for( var newBaddyIdx = 0; newBaddyIdx < 1; newBaddyIdx++ )
		{
			var baddyColourIdx = Math.floor( Math.random() * g_ZoopColours.length );
			var minBaddyAnimSpd = 0.05;
			var maxBaddyAnimSpd = 0.15;
			var baddyAnimSpd = minBaddyAnimSpd + ( Math.random() * ( maxBaddyAnimSpd - minBaddyAnimSpd ) );
		
			this.baddies.push( new ZoopBaddy( 
				newBabbyBoardPos.x + this.totalBoardPos.x, 
				newBabbyBoardPos.y + this.totalBoardPos.y, 
				g_ZoopColours[ baddyColourIdx ], // "red", 
				this.baddyDir, // "right", 
				baddyAnimSpd,
				frameIdx ) );
			vec2AddV( newBabbyBoardPos, this.addDir );	
		}		
	}	
	
	this.update = function( frameIdx )
	{
		// Iterating backwards because splice will effectively shuffle the items to the right down one if used causing us to skip an element as we increment the current index a
		for( var baddyIdx = 0; baddyIdx < this.baddies.length; )
		{
			var baddy = this.baddies[ baddyIdx ];
			
			if( baddy.totallyDead( frameIdx ) )
			{
				this.baddies.splice( baddyIdx, 1 );
			}
			else
			{
				baddyIdx++;
			}
		}		
	}

		
	this.draw = function( frameIdx )
	{
		for( var gx = 0; gx != SUB_BOARD_NUM_UNITS_X; ++gx )
		{
			for( var gy = 0; gy != SUB_BOARD_NUM_UNITS_Y; ++gy )
			{			
				var black = ( gx % 2 ) ^ ( gy % 2 );
				if( black )
				{
					context.fillStyle = this.colourA;
				}
				else
				{
					context.fillStyle = this.colourB;
				}
				
				context.fillRect(
					this.scrPos.x + ( gx * BOARD_UNIT_SIZE_X ),
					this.scrPos.y + ( gy * BOARD_UNIT_SIZE_Y ),
					BOARD_UNIT_SIZE_X,
					BOARD_UNIT_SIZE_Y );
			}
		}	
	
		// Draw baddies
		for( var baddyIdx in this.baddies )
		{
			this.baddies[ baddyIdx ].draw( frameIdx );			
		}		
	}

}